<template>
  <div id="xterm" class="xterm full-height full-width"></div>
</template>
<script setup>
import 'xterm/css/xterm.css'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
//import { AttachAddon } from 'xterm-addon-attach'
import { onBeforeUnmount, onMounted, ref } from 'vue'

const props = defineProps(['jobId'])
const fitAddon = new FitAddon()
const terminalElement = ref()
const socket = new WebSocket('ws://' + window.location.host + '/transflow/job/logs/' + props.jobId)
// 初始化 Terminal
const initTerminal = function () {
  terminalElement.value = new Terminal({
    rendererType: 'canvas', //渲染类型
    rows: 20, //行数
    //cols: cols, // 不指定行数，自动回车后光标从下一行开始
    convertEol: true, //启用时，光标将设置为下一行的开头
    // scrollback: 50, //终端中的回滚量
    disableStdin: true, //是否应禁用输入
    cursorBlink: true, //光标闪烁
    theme: {
      foreground: '#ECECEC', //字体
      background: '#1E1F22', //背景色
      cursor: 'help', //设置光标
      lineHeight: 20,
    },
  })
  // 2.webSocket初始化
  socket.onmessage = function (event) {
    terminalElement.value.writeln(event.data)
  }
  //const attachAddon = new AttachAddon(socket)
  //attachAddon.activate(terminalElement.value)
  fitAddon.activate(terminalElement.value)
  terminalElement.value.open(document.getElementById('xterm'))
  resizeScreen()
}
const resizeScreen = function (size) {
  try {
    fitAddon.fit() // fit时已经改变了terminalElement的宽度
    const rows = document.querySelector('#xterm').offsetHeight / 16
    // 窗口大小改变时触发xterm的resize方法，向后端发送行列数，格式由后端决定
    // 这里不使用size默认参数，因为改变窗口大小只会改变size中的列数而不能改变行数，所以这里不使用size.clos,而直接使用获取我们根据窗口大小计算出来的行列数
    terminalElement.value.resize(parseInt(rows), parseInt(size.height / 16))
    // this.terminalElement.onResize(() => {
    //   console.log(document.querySelector('#xterm').offsetWidth)
    //   this.sendJson({ data: 'resize', cols: this.terminalElement.cols, rows: this.terminalElement.rows, wp: this.wp, hp: this.hp })
    // })
  } catch (e) {
    console.log('e', e.message)
  }
}
onBeforeUnmount(() => {
  socket.close()
  fitAddon.dispose()
  terminalElement.value.close()
})
onMounted(() => {
  initTerminal()
})
defineExpose({ resizeScreen })
</script>

<style scoped>
.xterm ::-webkit-scrollbar {
  width: 8px;
  height: 8px;
  border-radius: 10px;
  background-color: #f5f5f5;
}

.xterm ::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  background-color: #f5f5f5;
}

.xterm ::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #447aff;
}
</style>
